package com.promise.jokerdream.ui.log

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Close
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.material3.*
import androidx.compose.runtime.*
import kotlinx.coroutines.launch
import androidx.compose.ui.Alignment
import androidx.activity.compose.BackHandler
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.promise.jokerdream.R
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.model.log.ExecutionLog
import com.promise.jokerdream.ui.theme.AppColors
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.toolbar.AppTopBar
import com.promise.jokerdream.ui.components.DangerAlertDialog
import com.promise.jokerdream.ui.components.LogItem
import com.promise.jokerdream.database.UserDataManager

/**
 * 执行记录视图
 */
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun ExecutionLogPage(
    modifier: Modifier = Modifier,
    navController: NavController? = null,
) {
    val context = LocalContext.current
    val historyManager = remember { ExecutionHistoryManager.getInstance(context) }
    val userDataManager = remember { UserDataManager.getInstance(context) }
    val logs by historyManager.logs.collectAsState()
    val listState = rememberLazyListState()
    val coroutineScope = rememberCoroutineScope()
    
    var searchText by remember { mutableStateOf("") }
    var showOnlySuccess by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    
    // 防重入的返回标志
    val hasPopBack = remember { mutableStateOf(false) }
    
    // 防重入的返回函数
    fun handleBack() {
        if (!hasPopBack.value) {
            hasPopBack.value = true
            navController?.popBackStack()
        }
    }
    
    // 获取当前用户ID
    val currentUserId = userDataManager.getCurrentAccount()?.userId ?: ""
    
    // 只在当前用户ID变化时刷新日志
    LaunchedEffect(currentUserId) {
        if (currentUserId.isNotEmpty()) {
            historyManager.refreshCurrentUserLogs()
        }
    }
    
    // 处理返回手势
    BackHandler {
        handleBack()
    }

    // 根据筛选条件过滤日志
    val filteredLogs = remember(logs, showOnlySuccess, searchText) {
        var filtered = logs
        
        // 按成功状态筛选
        if (showOnlySuccess) {
            filtered = filtered.filter { it.result != -2 && it.message != "很抱歉，系统繁忙，请稍后再试!" }
        }
        
        // 按搜索文本筛选
        if (searchText.isNotEmpty()) {
            filtered = filtered.filter { log ->
                log.operation.contains(searchText, ignoreCase = true) ||
                log.message.contains(searchText, ignoreCase = true)
            }
        }
        
        filtered
    }
    
    // 当日志列表更新时，自动滚动到顶部
    LaunchedEffect(logs.size) {
        if (logs.isNotEmpty()) {
            coroutineScope.launch {
                listState.animateScrollToItem(0)
            }
        }
    }
    
    // 当筛选条件改变时，自动滚动到顶部
    LaunchedEffect( searchText) {
        if (filteredLogs.isNotEmpty()) {
            coroutineScope.launch {
                listState.animateScrollToItem(0)
            }
        }
    }
    
    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // 统一的顶部导航栏
        AppTopBar(
            title = "执行记录",
            onBackClick = { handleBack() }
        )
        
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(AppColors.PageBackground)
                .padding(AppSpacing.pageHorizontal)
        ) {
            // 搜索框
            OutlinedTextField(
                value = searchText,
                onValueChange = { searchText = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppSpacing.searchBoxBottom),
                placeholder = { 
                    Text(
                        "搜索日志...",
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                    ) 
                },
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.Search,
                        contentDescription = "搜索",
                        modifier = Modifier.size(20.dp),
                        tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                    )
                },
                trailingIcon = {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(end = 12.dp)
                    ) {
                        // 过滤繁忙按钮
                        TextButton(
                            onClick = { showOnlySuccess = !showOnlySuccess },
                            modifier = Modifier.height(32.dp)
                        ) {
                            Text(
                                text = "过滤繁忙",
                                style = MaterialTheme.typography.bodySmall,
                                color = if (showOnlySuccess) {
                                    AppColors.SuccessText
                                } else {
                                    MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                                }
                            )
                        }
                        
                        // 清除搜索按钮
                        if (searchText.isNotEmpty()) {
                            IconButton(
                                onClick = { searchText = "" },
                                modifier = Modifier.size(24.dp)
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Close,
                                    contentDescription = "清除搜索",
                                    modifier = Modifier.size(18.dp),
                                    tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                                )
                            }
                        }
                        
                        // 清空按钮
                        IconButton(
                            onClick = { showDeleteDialog = true },
                            modifier = Modifier.size(24.dp)
                        ) {
                            Icon(
                                painter = painterResource(id = R.drawable.ic_delete),
                                contentDescription = "清空",
                                modifier = Modifier.size(18.dp),
                                tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                            )
                        }
                    }
                },
                singleLine = true,
                shape = RoundedCornerShape(16.dp),
                colors = OutlinedTextFieldDefaults.colors(
                    focusedBorderColor = Color.Transparent,
                    unfocusedBorderColor = Color.Transparent,
                    focusedContainerColor = Color.White,
                    unfocusedContainerColor = Color.White,
                    focusedTextColor = MaterialTheme.colorScheme.onSurface,
                    unfocusedTextColor = MaterialTheme.colorScheme.onSurface
                )
            )

            // 日志列表
            if (filteredLogs.isEmpty()) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    val emptyText = when {
                        searchText.isNotEmpty() && showOnlySuccess -> "未找到匹配的成功记录"
                        searchText.isNotEmpty() -> "未找到匹配的记录"
                        else -> "暂无记录"
                    }
                    
                    Text(
                        text = emptyText,
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            } else {
                LazyColumn(
                    state = listState,
                    modifier = Modifier.fillMaxSize(),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(
                        items = filteredLogs,
                        key = { it.id }
                    ) { log ->
                        LogItem(
                            log = log,
                            modifier = Modifier.animateItem(
                                fadeInSpec = tween(durationMillis = 300),
                                placementSpec = spring(stiffness = Spring.StiffnessMedium)
                            )
                        )
                    }
                }
            }
        }
    }
    
    // 删除确认弹窗
    DangerAlertDialog(
        show = showDeleteDialog,
        title = "确认删除",
        content = "确定要清空所有执行记录吗？此操作无法撤销。",
        confirmText = "清空",
        onDismiss = { showDeleteDialog = false },
        onConfirm = {
            historyManager.clearCurrentUserLogs()
            showDeleteDialog = false
        }
    )
}

